package com.wandong.cinema.service.impl;

import com.wandong.cinema.entity.Movie;
import com.wandong.cinema.entity.Show;
import com.wandong.cinema.service.MovieService;
import com.wandong.cinema.service.ShowService;
import com.wandong.cinema.util.IdGenerator;
import com.wandong.cinema.util.InputUtil;
import com.wandong.cinema.util.LogUtil;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

public class ShowServiceImpl implements ShowService {
    // 存储所有场次，场次ID作为键
    private static final Map<String, Show> SHOW_MAP = new ConcurrentHashMap<>();
    private static final SimpleDateFormat SDF = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    private MovieService movieService = new MovieServiceImpl();

    @Override
    public void addShow() {
        try {
            System.out.println("\n=== 添加场次 ===");
            System.out.print("请输入影片ID: ");
            String movieId = InputUtil.inputString();
            
            Movie movie = movieService.getMovieById(movieId);
            if (movie == null) {
                System.out.println("影片不存在");
                return;
            }
            
            System.out.print("请输入放映厅ID: ");
            String hallId = InputUtil.inputString();
            // 实际实现中应验证放映厅是否存在
            
            System.out.print("请输入放映时间(yyyy-MM-dd HH:mm): ");
            String timeStr = InputUtil.inputString();
            Date showTime = SDF.parse(timeStr);
            
            // 检查时间是否在当前时间之后
            if (showTime.before(new Date())) {
                System.out.println("放映时间不能早于当前时间");
                return;
            }
            
            System.out.print("请输入票价: ");
            double price = InputUtil.inputDouble();
            
            String showId = IdGenerator.generateShowId();
            Show show = new Show(showId, movieId, hallId, showTime, price, "未开始");
            
            SHOW_MAP.put(showId, show);
            LogUtil.log("添加场次：影片《" + movie.getName() + "》, 时间: " + timeStr + ", ID: " + showId);
            System.out.println("场次添加成功，场次ID: " + showId);
        } catch (ParseException e) {
            System.out.println("时间格式错误，正确格式为yyyy-MM-dd HH:mm");
        } catch (Exception e) {
            System.out.println("添加场次失败: " + e.getMessage());
        }
    }

    @Override
    public void deleteShow() {
        System.out.println("\n=== 删除场次 ===");
        System.out.print("请输入要删除的场次ID: ");
        String showId = InputUtil.inputString();
        
        if (!SHOW_MAP.containsKey(showId)) {
            System.out.println("场次不存在");
            return;
        }
        
        Show show = SHOW_MAP.get(showId);
        // 检查是否已售票，已售票则不能删除
        // 实际实现中应调用TicketService检查
        
        // 检查是否已过放映时间
        if (show.getShowTime().before(new Date())) {
            System.out.println("已过放映时间，不能删除");
            return;
        }
        
        SHOW_MAP.remove(showId);
        LogUtil.log("删除场次：ID: " + showId);
        System.out.println("场次删除成功");
    }

    @Override
    public void updateShow() {
        try {
            System.out.println("\n=== 修改场次 ===");
            System.out.print("请输入要修改的场次ID: ");
            String showId = InputUtil.inputString();
            
            if (!SHOW_MAP.containsKey(showId)) {
                System.out.println("场次不存在");
                return;
            }
            
            Show show = SHOW_MAP.get(showId);
            System.out.println("当前场次信息: " + show);
            
            // 检查是否已过放映时间
            if (show.getShowTime().before(new Date())) {
                System.out.println("已过放映时间，不能修改");
                return;
            }
            
            System.out.print("请输入新放映时间(yyyy-MM-dd HH:mm, 回车不修改): ");
            String timeStr = InputUtil.inputString();
            if (!timeStr.isEmpty()) {
                Date newTime = SDF.parse(timeStr);
                if (newTime.before(new Date())) {
                    System.out.println("放映时间不能早于当前时间，未修改时间");
                } else {
                    show.setShowTime(newTime);
                }
            }
            
            System.out.print("请输入新票价(回车不修改): ");
            String priceStr = InputUtil.inputString();
            if (!priceStr.isEmpty()) {
                double newPrice = Double.parseDouble(priceStr);
                show.setPrice(newPrice);
            }
            
            SHOW_MAP.put(showId, show);
            LogUtil.log("修改场次：ID: " + showId);
            System.out.println("场次修改成功");
        } catch (ParseException e) {
            System.out.println("时间格式错误，正确格式为yyyy-MM-dd HH:mm");
        } catch (Exception e) {
            System.out.println("修改场次失败: " + e.getMessage());
        }
    }

    @Override
    public void queryShows() {
        System.out.println("\n=== 场次查询 ===");
        System.out.println("1-查询所有场次 2-按影片查询 3-按日期查询");
        int choice = InputUtil.inputInteger();
        
        List<Show> result = new ArrayList<>();
        
        switch (choice) {
            case 1:
                result.addAll(SHOW_MAP.values());
                break;
            case 2:
                System.out.print("请输入影片ID: ");
                String movieId = InputUtil.inputString();
                for (Show show : SHOW_MAP.values()) {
                    if (show.getMovieId().equals(movieId)) {
                        result.add(show);
                    }
                }
                break;
            case 3:
                try {
                    System.out.print("请输入日期(yyyy-MM-dd): ");
                    String dateStr = InputUtil.inputString();
                    Date targetDate = new SimpleDateFormat("yyyy-MM-dd").parse(dateStr);
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(targetDate);
                    calendar.add(Calendar.DAY_OF_MONTH, 1);
                    Date nextDay = calendar.getTime();
                    
                    for (Show show : SHOW_MAP.values()) {
                        Date showTime = show.getShowTime();
                        if (showTime.after(targetDate) && showTime.before(nextDay)) {
                            result.add(show);
                        }
                    }
                } catch (ParseException e) {
                    System.out.println("日期格式错误");
                    return;
                }
                break;
            default:
                System.out.println("无效选择");
                return;
        }
        
        if (result.isEmpty()) {
            System.out.println("没有找到符合条件的场次");
            return;
        }
        
        // 按时间排序
        result.sort(Comparator.comparing(Show::getShowTime));
        
        System.out.println("\n查询结果:");
        for (Show show : result) {
            System.out.println(show);
        }
    }

    @Override
    public Show getShowById(String showId) {
        return SHOW_MAP.get(showId);
    }

    @Override
    public List<Show> getShowsByMovieId(String movieId) {
        List<Show> result = new ArrayList<>();
        for (Show show : SHOW_MAP.values()) {
            if (show.getMovieId().equals(movieId)) {
                result.add(show);
            }
        }
        return result;
    }

    @Override
    public List<Show> getShowsByDate(Date date) {
        List<Show> result = new ArrayList<>();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DAY_OF_MONTH, 1);
        Date nextDay = calendar.getTime();
        
        for (Show show : SHOW_MAP.values()) {
            Date showTime = show.getShowTime();
            if (showTime.after(date) && showTime.before(nextDay)) {
                result.add(show);
            }
        }
        return result;
    }

    @Override
    public void autoArrangeShows() {
        System.out.println("\n=== 自动排片 ===");
        System.out.print("请输入日期(yyyy-MM-dd): ");
        String dateStr = InputUtil.inputString();
        
        try {
            Date targetDate = new SimpleDateFormat("yyyy-MM-dd").parse(dateStr);
            
            // 检查日期是否在过去
            if (targetDate.before(new Date())) {
                System.out.println("不能为过去的日期排片");
                return;
            }
            
            // 1. 获取所有影片，按评分降序排列
            List<Movie> movies = movieService.getAllMovies();
            
            // 检查是否有影片
            if (movies.isEmpty()) {
                System.out.println("没有影片可供排片，请先添加影片");
                return;
            }
            
            movies.sort(Comparator.comparing(Movie::getScore).reversed());
            
            // 2. 定义放映时间段，黄金时段优先安排高评分影片
            List<String> timeSlots = Arrays.asList(
                "09:00", "11:30", "14:00", "16:30", 
                "19:00", "21:30" // 19:00-22:00为黄金时段
            );
            
            // 3. 模拟放映厅
            List<String> hallIds = Arrays.asList("H001", "H002", "H003");
            
            // 4. 自动排片逻辑
            int movieIndex = 0;
            int showCount = 0; // 记录实际排片数量
            for (String hallId : hallIds) {
                for (String timeSlot : timeSlots) {
                    if (movieIndex >= movies.size()) {
                        movieIndex = 0; // 循环安排影片
                    }
                    
                    Movie movie = movies.get(movieIndex);
                    String fullTimeStr = dateStr + " " + timeSlot;
                    Date showTime = SDF.parse(fullTimeStr);
                    
                    // 检查时间是否在当前时间之后
                    if (showTime.before(new Date())) {
                        movieIndex++;
                        continue;
                    }
                    
                    String showId = IdGenerator.generateShowId();
                    double price = timeSlot.compareTo("19:00") >= 0 ? 60 : 40; // 黄金时段票价更高
                    Show show = new Show(showId, movie.getMovieId(), hallId, showTime, price, "未开始");
                    
                    SHOW_MAP.put(showId, show);
                    LogUtil.log("自动排片：影片《" + movie.getName() + "》, 时间: " + fullTimeStr + ", 放映厅: " + hallId);
                    
                    movieIndex++;
                }
            }
            
            System.out.println("自动排片完成，共安排" + (hallIds.size() * timeSlots.size()) + "场电影");
        } catch (ParseException e) {
            System.out.println("日期格式错误，正确格式为yyyy-MM-dd");
        } catch (Exception e) {
            System.out.println("自动排片失败: " + e.getMessage());
        }
    }
    
    // 辅助方法，用于获取所有影片（实际应通过MovieService）
    private List<Movie> getAllMovies() {
        return new ArrayList<>(new MovieServiceImpl().getAllMovies());
    }
}